<script setup>
import { useUserStore } from '@/stores/user'
import { ref } from 'vue'
import { useRouter } from 'vue-router';
const router = useRouter()
const userStore = useUserStore()
const fd = ref({
  username: userStore.userInfo.username,
  password: '',
  newPassword: '',
  reNewPassword: ''
})

const rules = {
  password: [
    { required: true, message: '请输入旧密码', trigger: 'blur' },
    {
      validator(rule, value, callback) {
        if (value === userStore.userInfo.password) {
          callback()
        } else {
          callback(new Error('原密码错误'))
        }
      }, message: '原密码错误', trigger: 'blur'
    }
  ],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, message: '密码长度至少6位', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value == fd.value.password) callback(new Error('新密码不能与原密码相同'))
        callback()
      }
    }
  ],
  reNewPassword: [
    { required: true, message: '请确认新密码', trigger: 'blur' },
    { min: 6, message: '密码长度至少6位', trigger: 'blur' },
    {
      validator(rule, value, callback) {
        if (value === fd.value.newPassword) {
          callback()
        } else {
          ElMessage.error('两次密码输入不一致')
          callback(new Error('两次密码输入不一致'))
        }
      }, message: '两次密码输入不一致', trigger: 'blur'
    }
  ]
}
const form = ref()

const reset = () => {
  form.value.resetFields()
}
const submit = async () => {
  await form.value.validate()
  userStore.reset(fd.value)
  router.push({ name: 'login' })
}

</script>

<template>
  <div class="container">
    <el-form :label-position="'top'" ref="form" label-width="auto" :model="fd" :rules="rules">
      <el-form-item label="账户:">
        <el-input :modelValue="fd.username" style="width: 500px" type="text" disabled />
      </el-form-item>
      <el-form-item label="旧密码:" prop="password">
        <el-input v-model="fd.password" style="width: 500px" type="password" />
      </el-form-item>
      <el-form-item label="新密码:" prop="newPassword">
        <el-input v-model="fd.newPassword" style="width: 500px" type="password" />
      </el-form-item>
      <el-form-item label="确认密码:" prop="reNewPassword">
        <el-input v-model="fd.reNewPassword" style="width: 500px" type="password" />
      </el-form-item>
      <el-form-item>
        <el-button @click="reset">取消</el-button>
        <el-button type="primary" @click="submit">修改</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<style scoped>
.container {
  height: 100%;
  width: 100%;

}

form {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-direction: column;
}
</style>
